package org.springblade.modules.serial;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class WriteTimeoutHandler extends ChannelDuplexHandler {
	private static final Logger logger = LoggerFactory.getLogger(WriteTimeoutHandler.class);

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		// 所有写入操作都会经过这里，自动重置IdleStateHandler的计时器
		super.write(ctx, msg, promise);

		// 可以添加额外的日志记录
		logger.info("客户端写入操作，重置写超时计时器");
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			if (e.state() == IdleState.WRITER_IDLE) {
				logger.info("客户端 {} 超过 {} 秒未写入，断开连接",
					ctx.channel().remoteAddress(),
					30);
				ctx.close();
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.error("连接异常", cause);
		ctx.close();
	}
}
